package com.study.Socket;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SocketService {
    private static ServerSocket serverSocket=null;

    //并发数是5
    private static ExecutorService threadPool=Executors.newFixedThreadPool(5);
    public static void main(String[] args) throws Exception{
        try{
            serverSocket =new ServerSocket(10086);
            while(true){
                Socket socket=serverSocket.accept();
                threadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        int num=0;
                        InputStream  is=null;
                        OutputStream os=null;
                        try{
                            is=socket.getInputStream();
                            os=socket.getOutputStream();
                            int len = 0;
                            byte[] buf = new byte[1024];
                            while ((len=is.read(buf))!=-1)
                            {
                                System.out.println("client saying: "+new String(buf,0,len));
                                os.write(("服务端发送消息:"+(++num)).getBytes());
                                os.flush();
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                        }finally {
                           try{
                               os.close();
                               is.close();
                               socket.close();
                           }catch (Exception e){
                               e.printStackTrace();
                           }
                        }
                    }
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {

            if(serverSocket!=null) serverSocket.close();
        }

    }
}
